#!/usr/bin/env python
import sys
from XmlTools import SMKernel
from glat2 import spect

def extract_plot(inxml, sname, **kwds):
    xobj = SMKernel.SourceModel(inxml, raiseErr=True)
    spobj = spect.get_specobj_from_xmlsrc(xobj[sname])
    return spobj.plot_spec(**kwds)

lss = ['-', '--', '-.', ':']

if __name__ == '__main__':
    import argparse
    from matplotlib import pyplot as plt

    parser = argparse.ArgumentParser(description='A quick tool to draw the spectra in the xmlfiles', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("instr", type=str, nargs='+',
        help="""the string to indicate the input xmlfile and sname with the
form: xmlfile?sname, e.g. model1.xml?isotropic,
"model1.xml?4FGL J1427.0+2348"
- if the sname is the same as the previous one, you can ignore
  the sname part: model1.xml?isotropic model2.xml model3.xml
- if the xmlfile is the same as the previous one, you can ignore
  the xmlfile part: model.xml?sname1 ?sname2 ?sname3""")
    parser.add_argument("-outfile", type=str, default=None,
        help='the name of the outfile, default: None')
    parser.add_argument("-emin", type=float, default=100.,
        help='the lower bound of E plot in [MeV], default: 100')
    parser.add_argument("-emax", type=float, default=1e5,
        help='the upper bound of E plot in [MeV], default: 1e5')
    parser.add_argument("-alpha", type=float, default=2,
        help='the index of spectra raised by E^alpha * Sp(E), default: 2')
    args = parser.parse_args()

    fig = None
    xmlfile, sname = None, None
    for idx, instr in enumerate(args.instr):
        if '?' in instr:
            xmlfile_, sname_ = instr.split('?')
        else:
            xmlfile_ = instr

        if xmlfile_:
            xmlfile = xmlfile_
        if sname_:
            sname = sname_
        if xmlfile is None or sname is None:
            raise RuntimeError('the xmlfile and source name must be specified in the first instr with "?": %s'%instr)

        fig = extract_plot(xmlfile, sname, emin=args.emin, emax=args.emax, ne=200, alpha=args.alpha, fig=fig,
            plot_kwds={'label': '%s?%s'%(xmlfile, sname), 'ls': lss[idx%4]})

    if args.outfile:
        fig.savefig(args.outfile)
    else:
        plt.show()
